package com.zsr.orderservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsr.commonutils.entity.vo.CourseInfoCommonVo;
import com.zsr.commonutils.entity.vo.UcenterMemberInfoCommonVo;
import com.zsr.orderservice.client.EduClient;
import com.zsr.orderservice.client.UcenterClient;
import com.zsr.orderservice.constants.OrderStatus;
import com.zsr.orderservice.constants.OrderPayType;
import com.zsr.orderservice.entity.TOrder;
import com.zsr.orderservice.mapper.TOrderMapper;
import com.zsr.orderservice.service.TOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsr.orderservice.utils.OrderNoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author zsr
 * @since 2021-06-22
 */
@Service
public class TOrderServiceImpl extends ServiceImpl<TOrderMapper, TOrder> implements TOrderService {

    @Autowired
    private EduClient eduClient;

    @Autowired
    private UcenterClient ucenterClient;


    @Override
    public String saveOrder(String courseId, String memberIdByJwtToken) {
        //远程调用课程服务，根据课程id获取课程信息
        CourseInfoCommonVo courseDto = eduClient.getCourseInfoDto(courseId);

        //远程调用用户服务，根据用户id获取用户信息
        UcenterMemberInfoCommonVo ucenterMember = ucenterClient.getInfo(memberIdByJwtToken);
        TOrder order = null;

        QueryWrapper<TOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        wrapper.eq("member_id", memberIdByJwtToken);
        wrapper.eq("status", OrderStatus.NOPAY.getCode());
        order = baseMapper.selectOne(wrapper);

        if (order == null) {
            order=new TOrder();
            //创建订单
            order.setOrderNo(OrderNoUtil.getOrderNo());
            order.setCourseId(courseId);
            order.setCourseTitle(courseDto.getTitle());
            order.setCourseCover(courseDto.getCover());
            order.setTeacherName(courseDto.getTeacherName());
            order.setTotalFee(courseDto.getPrice());
            order.setMemberId(memberIdByJwtToken);
            //TODO 手机号未写入订单
            //order.setMobile(ucenterMember.getMobile());
            order.setNickname(ucenterMember.getNickname());
            order.setStatus(OrderStatus.NOPAY.getCode());
            order.setPayType(OrderPayType.WX.getCode());
            baseMapper.insert(order);
        }

        return order.getOrderNo();
    }
}
